// 获取远程文件
const proxy = require('http-proxy-middleware');

const {
  LINK,
  createSign
} = require('./util');

module.exports = proxy({
  target: LINK,
  changeOrigin: true,
  logLevel: 'error',
  pathRewrite: {
    '/g': '/aiimage',
  },
  onProxyReq(proxyReq, req) {
    const url = req.url.split('?')[0];
    const date = new Date().toUTCString();
    const Authorization = createSign('GET', '', url, date);

    proxyReq.setHeader('Date', date);
    proxyReq.setHeader('Authorization', Authorization);
  },
  onProxyRes(proxyRes, req, res) {
    // res.status(401).send('文件已经失效');

    if (req.query.download) {
      proxyRes.headers['Content-disposition'] = `attachment;filename=${req.query.name}`;
      proxyRes.headers['Content-Type'] = `application/octet-stream`;
    }
  }
});
